package cn.lizemin.mybatisplus.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author: lizemin
 * @version: 1.0
 */
@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("insert自动填充......");
        //告诉mybatis填充什么
        this.strictInsertFill(metaObject,"createTime", LocalDateTime.class,LocalDateTime.now());
        this.strictInsertFill(metaObject,"updateTime", LocalDateTime.class,LocalDateTime.now());

        //如果age属性没有赋值，我们才自动填充
        Object age = this.getFieldValByName("age", metaObject);
        if (age == null){
            log.info("insert age 自动填充");
            this.strictInsertFill(metaObject,"age", Integer.class,28);

        }



        //自动填充author字段，首先看它是否存在。通过判断来提高程序的执行效率
        boolean author = metaObject.hasSetter("author");
        if (author){
            log.info("author自动填充......");
            this.strictInsertFill(metaObject,"author", String.class,"悟空");

        }


    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("update自动填充......");
        this.strictUpdateFill(metaObject,"updateTime", LocalDateTime.class,LocalDateTime.now());

    }



}
